import common from '../../config/js/common';

var currentPage

Page({
  data:{
    id:null,
    title:""
  },
  onLoad: function (params){
    let Pages = getCurrentPages()
    currentPage = Pages[Pages.length - 1]

    this.setData({
      id: params.id,
      title: params.title
    })
  },
  submitPoem: function (event) {
    console.log(event);
  },
  formSubmit: function (e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value)
    let contentInit = e.detail.value.reciteContent
    let contentAfterHandle = contentInit.replace(/[^\u4e00-\u9fa5]/gi, "")
    if (contentAfterHandle){
      console.log("发送背诵检查请求，内容：" + contentAfterHandle)
      
      let token = wx.getStorageSync('token')
      if (token) {
        wx.showLoading({
          title: '龟速运行中',
        })
        wx.request({
          url: common.content_center + "poem/checkRecite",
          method: 'GET',
          header: {
            'WX-TOKEN': token
          },
          data: {
            poemId: currentPage.data.id,
            reciteContent: contentAfterHandle
          },
          success(res) {
            wx.hideLoading()
            let data = res.data;
            console.log("请求确认背诵 后台返回")
            console.log(data)
            if (data.code == 0) {// 服务端调用成功
              let reciteResult = data.data.reciteResult
              if (reciteResult == "wrong"){
                common.openConfirm("抱歉，提交内容和原诗不匹配，默写失败", "返回首页", "好的", function () {
                  wx.switchTab({
                    url: "/pages/index/index"
                  })
                })
              } else if (reciteResult == "good"){
                common.openConfirm("恭喜，默写内容和原诗匹配，通过！", "返回首页", "好的", function () {
                  wx.switchTab({
                    url: "/pages/index/index"
                  })
                })
              } else {
                common.showTip("这一定是个bug，请反馈给程序员，谢谢！")
              }
              
            } else if (data.code == 3) { // 未登录
              common.openConfirm("还未登录", "去登录", "拒绝登录", function () {
                wx.switchTab({
                  url: "/pages/my/my"
                })
              })
            } else if (data.code == 4) { // 重复背诵
              common.showTip("这首诗您已经背诵过了！",function(){
                wx.switchTab({
                  url: "/pages/index/index"
                })
              })
            }
          },
          fail(res) {
            wx.hideLoading()
            console.log("请求确认背诵 服务调用异常：" + res)
          },
        })
      }else{
        common.openConfirm("还未登录", "去登录", "拒绝登录", function () {
          wx.switchTab({
            url: "/pages/my/my"
          })
        })
      }
    }else{
      common.showTip("输入的汉字空空如也！",function(){
        console.log("空空如也！")
      })
    }
  }
});